#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

class Sock{
public:
    static int Socket(){
        int sock = socket(AF_INET, SOCK_STREAM, 0);
        if (sock < 0){
          std::cerr << "Listen socket create errno" << errno << std::endl;
          exit(1);
        }
        std::cout << "Socket create success" << std::endl;
        return sock;
    }
    static void Bind(int sock, uint16_t port){
      struct sockaddr_in local;
      memset(&local, 9, sizeof(local));
      local.sin_addr.s_addr = INADDR_ANY;
      local.sin_family = AF_INET;
      local.sin_port = htons(port);
      if (bind(sock, (struct sockaddr*)&local, sizeof(local)) < 0){
        std::cerr << "Bind socket error" << errno << std::endl;
        exit(2);
      }
      std::cout << "Bind success" << std::endl;
    }
    static void Listen(int sock){
      if (listen(sock, 5)){
        std::cerr << "Listen system call errno" << errno << std::endl;
        exit(3);
      }
    }
    static int Accept(int sock){
      struct sockaddr_in peer;
      socklen_t len = sizeof(peer);
      int fd = accept(sock, (struct sockaddr*)&peer, &len); 
      if (fd < 0){
        std::cerr << "Accept connection errno";
        return -1;
      }
      std::cout << "accept success" << std::endl;
      return fd;
    }
    static void Connect(int sock ,std::string ip, uint16_t port){
      struct sockaddr_in peer;
      socklen_t peer_len = sizeof(peer);
      memset(&peer, 0, sizeof(peer));
      peer.sin_addr.s_addr = inet_addr(ip.c_str());
      peer.sin_port = htons(port);
      peer.sin_family = AF_INET;
      if (connect(sock, (struct sockaddr*)&peer, peer_len) < 0){
        std::cerr << "connect server errno" << errno << std::endl;
        exit(-1);
      }
      std::cout << "Conect success" <<std::endl;
    }
};
